"""
自定义管理命令, 添加方法

- app.add_manager_command
- @app.cli.command
- @click.command, 如下，example 命令

提示：
    $ flask --help

使用：
    $ python manage.py example test
    $ flask example test
"""
import os

import click
from flask.cli import with_appcontext

# try:
#     app = sys.modules["app"].adp_app
# except KeyError:
#     try:
#         from flask import current_app as app
#         if isinstance(app, Flask):
#             raise ImportError
#     except ImportError:
#         app = sys.modules["app"].App(__name__)


@click.command("example", context_settings={"ignore_unknown_options": True})
@click.argument("any_attr", nargs=-1, type=click.UNPROCESSED)
def example(any_attr):
    """自定义命令行示例"""
    print(f"===>>> This is example command {any_attr}")


@click.command("deploy")
@with_appcontext
def deploy():
    """迁移数据库."""
    from pathlib import Path

    from flask_migrate import init, migrate, upgrade

    from tools import db

    abspath = os.path.join(os.path.dirname(os.path.abspath(__file__)))
    file_path = Path(abspath).parent.parent / "migrations"
    if file_path.exists():
        import shutil

        shutil.rmtree(file_path)
    init()
    db.session.execute("drop table if exists alembic_version;")
    migrate()
    upgrade()


@click.command("releaseSpace")
@with_appcontext
def releaseSpace():
    """销毁已过期的虚拟机"""
    from scripts.releaseSpace import RangeVmBase

    obj = RangeVmBase()
    # obj.sync_op_vm()
    obj.sync_op_net()


@click.command("syncFlow")
@with_appcontext
def syncFlow():
    from scripts.releaseSpace import Synctap

    obj = Synctap()
    obj.check_agent_start_time()
